package com.czk.api.scan;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/6/3 15:13
 */
public class ScanDemo {
    private static Connection connection = null;
    private static Admin admin = null;

    static {
        // 静态代码块初始化
        // 创建配置类
        Configuration configuration = HBaseConfiguration.create();
        // zookeeper连接
        configuration.set("hbase.zookeeper.quorum", "192.168.25.133");
        // 端口
        configuration.set("hbase.zookeeper.property.clientPort", "2181");
        //
        try {
            connection = ConnectionFactory.createConnection(configuration);
            admin = connection.getAdmin();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接
     */
    public static void close() {
        try {
            if (admin != null) {
                admin.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }

    }

    public static void main(String[] args) throws IOException {
        scanTable("stu");
    }

    public static void scanTable(String tableName) throws IOException {
        // 拿到表对象
        Table table = connection.getTable(TableName.valueOf(tableName));
        // 构建scan对象
        Scan scan = new Scan();
        // 扫描表
        ResultScanner scanner = table.getScanner(scan);
        // 解析
        for (Result result : scanner) {
            // 解析
            Cell[] cells = result.rawCells();
            for (Cell cell : cells) {
                // 打印数据
                byte[] bytes = CellUtil.cloneFamily(cell);
                // 转为string
                // 列族
                String CF = Bytes.toString(bytes);
                // 列名
                String CN = Bytes.toString(CellUtil.cloneQualifier(cell));
                // 值
                String value = Bytes.toString(CellUtil.cloneValue(cell));
                System.out.println("CF=" + CF);
                System.out.println("CN=" + CN);
                System.out.println("value=" + value);
                System.out.println(cell.getTimestamp());
            }
        }
        // 关闭
        table.close();
        close();
    }
}
